package com.igroupes.ovineherd.handler;

import com.igroupes.ovineherd.enums.BooleanKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * java中的Boolean和jdbc中的char转化
 */
@Slf4j
public class BooleanTypeHandler implements TypeHandler {
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Object o, JdbcType jdbcType) throws SQLException {
        Boolean b = (Boolean) o;
        Integer value = b ? BooleanKey.TRUE.getCode() : BooleanKey.FALSE.getCode();
        preparedStatement.setInt(i, value);
    }

    @Override
    public Object getResult(ResultSet resultSet, String s) throws SQLException {
        Integer str = resultSet.getInt(s);
        Boolean rt = Boolean.FALSE;
        if (str.equals(BooleanKey.TRUE.getCode())){
            rt = Boolean.TRUE;
        }
        return rt;
    }

    @Override
    public Object getResult(ResultSet resultSet, int i) throws SQLException {
        Boolean b = resultSet.getBoolean(i);
        return b ? BooleanKey.FALSE.getCode() : BooleanKey.TRUE.getCode();
    }

    @Override
    public Object getResult(CallableStatement callableStatement, int i) throws SQLException {
        Boolean b = callableStatement.getBoolean(i);
        return b ? BooleanKey.FALSE.getCode() : BooleanKey.TRUE.getCode();
    }
}
